<template>
  <u-navbar
    back-text=""
    title=""
    :background="navBackground"
    back-icon-size="30rpx"
    :is-fixed="true"
    :immersive="true"
    title-color="#fff"
    back-icon-color="#fff"
    :custom-back="handleBack"></u-navbar>
	<view style="overflow: hidden;">
		<camera device-position="back" flash="off" frame-size="small" @error="error"></camera>
		<canvas canvas-id="myCanvas" class="my-canvas"></canvas> <!-- :style="{width: myCanvasWidth + 'px', height: myCanvasHeight + 'px'}" -->
		
		<view class="scan-line">
			<img class="scan-line-img" src="/pages/objIdentify/static/image/obj-identify/scaning.png" />
		</view>
		
		<view class="prew-img" style="position: absolute; top: 0%; left:0%; width: 100%; height: 100%;">
			<img :src="prewImage" style="width:120%; height: 100%; margin:-10%; margin-top: 0%;"/>
		</view>
		
		<view v-for="(item, index) in pointList" :key="item.class" 
			:style="{position: 'absolute', top: item.pointTop + 'px', left: item.pointLeft + 'px'}">
			<img class="scan-point-img" @click="clickNavigateTo(item.id)" src="/pages/objIdentify/static/image/obj-identify/selected-point.png"/>
			<view class="scan-point-text">{{ item.cls_name }}</view>
		</view>
				
	</view>
</template>

<script>
import api from '@/config/api'
import uNavbar from '@/components/navbar/index.vue'
	export default {
		data() {
			return {
				setTimeoutTakePhoto: null,
				IntervalTime: 2500,
				pointList: [],
				// identifyUrl: 'http://47.104.0.169:8000', // 识别算法接口请求地址前缀
				identifyUrl: api.identifyUrl,
				// identifyUrl: 'http://47.105.121.63:8000',
				myCanvasWidth: 30,
				myCanvasHeight: 30,
        prewImage: '',
        navBackground: {
          background: 'transparent'
        }
			};
  },
    components: {
      uNavbar
    },
		onLoad() {
			
		},
		onShow() {
			this.prewImage = "";
			
			this.timedPhotographing();
			
			uni.getSystemInfo({
			  success: (info) => {
			    // console.log('Window Width: ' + info.windowWidth);
			    // console.log('Window Height: ' + info.windowHeight);
				this.myCanvasWidth = info.windowWidth;
				this.myCanvasHeight = info.windowHeight;
			  }
			});
			
		},
		methods: {
			handleBack() {
        uni.navigateBack({
          fail() {
            uni.redirectTo({
              url: '/pages/objIdentify/indexList'
            })
          }
        })
      },
			timedPhotographing() {
			  const ctx = wx.createCameraContext();
			  this.setTimeoutTakePhoto = setInterval(() => {
			    this.getPhoto(ctx);
			  }, this.IntervalTime);
			},
			endTimedPhotograph() {
			  clearInterval(this.setTimeoutTakePhoto);
			  this.setTimeoutTakePhoto = null;
			},
			getPhoto(ctx) {
			  let that = this;
			  let bool = true;
			  let listener = ctx.onCameraFrame((frame) => {
				  // console.log('Frame Width: ' + frame.width);
				  // console.log('Frame Height: ' + frame.height);
				  
				  // console.log('Frame Width: ' + frame.width*wx.getSystemInfoSync().pixelRatio);
				  // console.log('Frame Height: ' + frame.height*wx.getSystemInfoSync().pixelRatio);
			    if (bool) {
			      let data = new Uint8Array(frame.data);
			      let clamped = new Uint8ClampedArray(data);
			     
			      wx.canvasPutImageData({
			        canvasId: 'myCanvas',
			        x: 0,
			        y: 0,
			        width: frame.width,
			        height: frame.height,
			        data: clamped,
			        success(res) {
			          // 转换临时文件
			          wx.canvasToTempFilePath({
			            x: 0,
			            y: 0,
			            width: frame.width,
			            height: frame.height,
						// destWidth: frame.width*wx.getSystemInfoSync().pixelRatio,
			   //          destHeight: frame.height*wx.getSystemInfoSync().pixelRatio,
			            canvasId: 'myCanvas',
			            success(res) {
							// console.log(res)
							const tempFile = res.tempFilePath;
							
							that.requestAi(tempFile, frame);
							
			            },
			            fail(err) {
			              console.log('转换失败', err);
			            }
			          }, that);
			        },
			        fail(err) {
			          console.log("canvasPutImageData 失败", err);
			        }
			      }, that);
			    }
			    bool = false;
			    listener && listener.stop() && (listener = null);
			  });
			  listener.start();
			},
			requestAi(tempFile, frame){
				const uploadTask = uni.uploadFile({
					url: this.identifyUrl + '/predict',
					method: 'POST',
					// header: {
					// 	'content-type': 'multipart/form-data'
					// },
					filePath: tempFile,
					name: 'file', // 参数名
					success: uploadRes => {
						// console.log('upload success:', uploadRes);
						if(uploadRes.statusCode == 200 && JSON.parse(uploadRes.data).detections.length > 0){
																					
							this.pointList = [];
							const idMap = {}; // 用于记录每个id的最高confidence
							//数据过滤： 1、置信值小于0.5的剔除掉。 2、重复id的提出掉
							console.log("1、置信值小于0.5的剔除掉。 2、重复id的提出掉", JSON.stringify(JSON.parse(uploadRes.data).detections));
							JSON.parse(uploadRes.data).detections.forEach(item => {
								// 条件1：confidence >= 0.5
								if (item.confidence >= 0.5) {
									// 条件2：检查是否是当前id中confidence最高的
									if (!idMap[item.id] || item.confidence > idMap[item.id].confidence) {
										// 如果之前已经存在该id的项，从结果中移除
										if (idMap[item.id]) {
											const index = this.pointList.findIndex(i => i.id === item.id);
											if (index !== -1) {
												this.pointList.splice(index, 1);
											}
										}
										// 添加当前项到结果中
										this.pointList.push(item);
										// 更新idMap记录
										idMap[item.id] = { confidence: item.confidence };
									}
								}
							});
							
							if(this.pointList.length > 1){
								this.prewImage = tempFile;
								//卸载定时扫描
								this.endTimedPhotograph();
							}
							
							console.log("1、置信值小于0.5的剔除掉。 2、重复id的提出掉", JSON.stringify(this.pointList));
							
							
							
							//加载标记点位图标
							// this.pointList = JSON.parse(uploadRes.data).detections;
							this.onvertBboxToCss(frame.width, frame.height);
							
							//识别到单个
							// if(this.pointList.length == 1 && this.pointList[0].confidence > 0.8){
							if(this.pointList.length == 1){
								setTimeout(() => {
									this.clickNavigateTo(this.pointList[0].id);
								}, 1500)
							}
							
						}
					},
					fail: uploadError => {
						console.error('upload error:', uploadError);
					}
				});
			},
			clickNavigateTo(id){
				uni.navigateTo({
					url: '/pages/objIdentify/objIdentifyRes?curObjId=' + id
				});	
												
				this.pointList = [];
				
			},
			onvertBboxToCss(img_width, img_height){
				this.pointList.forEach((item, index, array) => {
					let bbox = item.bbox;
					
					// console.log('图像识别定位点:', bbox)
					// // 计算 bbox 的中心点
					// let x_center = (bbox[0] + bbox[2]) / 2 / wx.getSystemInfoSync().pixelRatio;
					// let y_center = (bbox[1] + bbox[3]) / 2 / wx.getSystemInfoSync().pixelRatio;
					
					// // 将中心点转换为相对于容器的百分比
					// let center_x = (x_center / img_width) * 100;
					// let center_y = (y_center / img_height) * 100;
					
					
					// array[index].pointLeft = this.myCanvasWidth * center_x / img_width;
					// array[index].pointTop = this.myCanvasHeight * center_y / img_height;
					
					
					
					array[index].pointLeft = (bbox[0] + bbox[2]) / 2 / wx.getSystemInfoSync().pixelRatio * (this.myCanvasWidth / img_width);
					array[index].pointTop = (bbox[1] + bbox[3]) / 2 / wx.getSystemInfoSync().pixelRatio * (this.myCanvasHeight / img_height);
					
				});
				
				console.log("获取到所有识别的要素", JSON.stringify(this.pointList));
				
			},
			error(e) {
				console.log(e.detail);
			},
		}
	}
</script>

<style lang="scss" scoped>
	.arrow-icon {
	  display: inline-block;
	  width: 24px;   /* 控制整体大小 */
	  height: 24px;
	  cursor: pointer;
	  
	  position: absolute;
	  top: 55px;
	  left: 10px;
	  z-index: 99;
	  color: #ffffff;
	}
	
	/* 通过旋转矩形创建箭头线条 */
	.arrow-icon::before {
	  content: '';
	  position: absolute;
	  top: 50%;
	  left: 25%;
	  width: 12px;    /* 控制箭头长度 */
	  height: 2px;    /* 控制线条粗细 */
	  background: currentColor;
	  transform: rotate(-45deg);
	  transform-origin: left center;
	}
	
	.arrow-icon::after {
	  content: '';
	  position: absolute;
	  top: 50%;
	  left: 25%;
	  width: 12px;    /* 控制箭头长度 */
	  height: 2px;    /* 控制线条粗细 */
	  background: currentColor;
	  transform: rotate(45deg);
	  transform-origin: left center;
	}
	
	/* 交互效果 */
	.arrow-icon:hover {
	  opacity: 0.7;
	}
	
	.arrow-icon:active {
	  transform: scale(0.9);
	}
	
	camera{
		width: 100%; 
		height: 100vh;
	}
	
	.scanBtn{
		position: absolute;
		bottom: 0px;
	}
	
	.scan-line{
		position: absolute;
		top: 0px;
		width: 100%;
		height: 32px;
		animation-duration: 3.5s; 
		animation-timing-function: linear; 
		animation-delay: 0s;
		animation-iteration-count: infinite; 
		animation-direction: normal;
		animation-fill-mode: none;
		animation-play-state: running; 
		animation-name: bRTaPl;
		
		.scan-line-img{
			width: 100%;
			height: 32px;
		}

	}
	
 	@keyframes bRTaPl{
	  0% {
	    transform: translate(0px, 20vh);
	  }
	  50% {
	    transform: translate(0px, 50vh);
	  } 
	  100% {
	    transform: translate(0px, 80vh);
	  }
	}
	
	.scan-point-img{
		position: absolute;
		width: 60px;
		height: 60px;
	}
	
	.scan-point-text{
		color: #fff;
		font-size: 14px;
	}
	
	.my-canvas{
		position: absolute; 
		width: 100%;
		height: 100%;
		top: -200%; 
		left: -200%;
	}
</style>